package com.hakgc.rent.web.servlet;

import com.alibaba.fastjson.JSON;
import com.hakgc.rent.constant.SystemConstant;
import com.hakgc.rent.dto.Page;
import com.hakgc.rent.dto.Result;
import com.hakgc.rent.entity.District;
import com.hakgc.rent.service.DistrictService;
import com.hakgc.rent.service.impl.DistrictServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 访问区县列表页面的Servlet
 *
 * @author Xing.Jiejian
 * @date 2020/11/9
 */
@WebServlet(name = "DistrictListServlet", urlPatterns = "/rent/districts")
public class DistrictListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数有页码，每页显示数量
        int pageNo = 1;
        String strPageNo = request.getParameter("pageNo");
        if (strPageNo != null && !"".equals(strPageNo)) {
            pageNo = Integer.parseInt(strPageNo);
        }
        int pageSize = SystemConstant.PAGE_SIZE;
        String strPageSize = request.getParameter("pageSize");
        if (strPageSize != null && !"".equals(strPageSize)) {
            pageSize = Integer.parseInt(strPageSize);
        }
        // 获取查询条件
        String name = request.getParameter("districtName");
        if (name != null) {
            name = name.trim();
        }

        // 创建区县业务类对象
        DistrictService districtService = new DistrictServiceImpl();
        // 获取区县的总条数
        int totalCount = districtService.getAllCount(name);
        // 计算总页码数
        int pageCount = (totalCount + pageSize - 1) / pageSize;
        // 限定页码范围不能超限
        if (pageNo < 1) {
            // 如果页码小于第一页，则直接访问第一页
            pageNo = 1;
        }
        if (pageNo > pageCount) {
            // 如果页码超过最大页，则显示最后一页
            pageNo = pageCount;
        }

        // 查询获取分页区县集合(不需要关联街道信息)
        List<District> districts = districtService.findByPage(name, pageNo, pageSize);


        Result<Page<District>> result = new Result<>();
        Page<District> page = new Page<>(districts,pageNo,pageSize,totalCount,pageCount);
        result.setData(page);

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(result));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/rent/districtList.jsp").forward(request,response);

    }
}
